import store from '../store';
import childProcess from 'child_process';
import ServeConfig, { IServer } from '~common/serve';
import { BrowserWindow, ipcMain, IpcMainEvent } from 'electron';
import { IpcMainEventEnum, IpcRendererEventEnum } from '~common/enum';

// JS Lib 库访问
function jsLibPath(dir: string) {
    return `${store.state.runtime.paths.jsLib}/${dir}`;
}

let serveConfigIns: ServeConfig;

/**
 * Serve 服务进程控制
 */
function serveProcessControl(window: BrowserWindow | null): void {
    // ...
    serveConfigIns = new ServeConfig();
    const childProcessMap: Record<string, childProcess.ChildProcess> = {};

    // Serve Renderer is ready
    ipcMain.on(IpcMainEventEnum.SERVE_RENDERER_READY, () => {
        window?.webContents.send(IpcRendererEventEnum.GET_SERVE_CONFIG, { serverConfig: serveConfigIns.config });
    });

    // 添加服务
    ipcMain.on(IpcMainEventEnum.ADD_SERVE_PROCESS, (event: IpcMainEvent, server: IServer) => {
        serveConfigIns.addServer(server);
    });

    // 修改服务
    ipcMain.on(IpcMainEventEnum.MOD_SERVE_PROCESS, (event: IpcMainEvent, server: IServer) => {
        serveConfigIns.modServer(server);
    });

    // 删除服务
    ipcMain.on(IpcMainEventEnum.DEL_SERVE_PROCESS, (event: IpcMainEvent, server: IServer) => {
        serveConfigIns.delServer(server);
    });

    // 运行服务
    ipcMain.on(IpcMainEventEnum.RUN_SERVE_PROCESS, (event: IpcMainEvent, server: IServer) => {
        const cp = childProcess.fork(jsLibPath('lv-server/index.js'));
        childProcessMap[server.serverName] = cp;
        cp.on('exit', () => {});
        cp.on('message', msg => {
            switch (msg) {
                case 'start_server': {
                    // 发送服务配置数据后，子进程会自动启动服务
                    cp.send(server);
                    break;
                }
                case 'server_is_running': {
                    // 服务运行成功
                    serveConfigIns.modServer(server);
                    break;
                }
            }
        });
    });

    // 退出服务
    ipcMain.on(IpcMainEventEnum.CLS_SERVE_PROCESS, (event: IpcMainEvent, server: IServer) => {
        if (server.isRun) {
            childProcessMap[server.serverName].kill();
            delete childProcessMap[server.serverName];
            serveConfigIns.modServer(server);
        }
    });
}

export { serveProcessControl };
